package com.hzchendou.blog.demo.example;

import com.hzchendou.blog.demo.entity.AuthorDO;
import com.hzchendou.blog.demo.entity.BlogDO;
import com.hzchendou.blog.demo.enums.BlogStatusEnums;
import com.hzchendou.blog.demo.mapper.AuthorMapper;
import com.hzchendou.blog.demo.mapper.BlogMapper;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

/**
 * 案例1
 *
 * @Date: 2022-07-04 15:46
 * @since: 1.0
 */
@Slf4j
public class Case1 extends AbstractCase {

    @Override
    public void run() throws IOException {
        /// 使用Java 7提供的 try-with-resource写法，让JVM自动完成资源关闭操作
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            //// 获取Mapper接口示例（底层使用了JDK的Proxy.newProxyInstance方法创建代理）
            BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
            //// 创建博文记录
            BlogDO blog = new BlogDO();
            blog.setTitle("时间海绵博文");
            blog.setAuthorId(1);
            blog.setTags("博文、时间海绵");
            blog.setStatus(BlogStatusEnums.VALID);
            int res = blogMapper.insert(blog);
            log.info("创建时间海绵博文结果: {}", res);
            /// 需要提交事务确保提交成功，只有提交了事务才能在数据库中正确插入数据
            sqlSession.commit();

            //// 查询文章记录
            List<BlogDO> blogs = blogMapper.selectAll();
            log.info("博文信息列表: {}", blogs);

            //// 获取Mapper接口示例（底层使用了JDK的Proxy.newProxyInstance方法创建代理）
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            /// 创建文章作者记录
            AuthorDO authorDO = new AuthorDO();
            authorDO.setId(1);
            authorDO.setUsername("时间海绵");
            authorDO.setRemark("不知名博主");
            res = authorMapper.insert(authorDO);
            log.info("创建时间海绵作者结果: {}", res);
            /// 查询所有作者信息
            List<AuthorDO> authors = authorMapper.selectAll();
            log.info("作者信息列表: {}", authors);
            sqlSession.commit();
        }
    }
}
